package com.android.bhwallet.app.Main.UI;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.bhwallet.R;
import com.android.bhwallet.utils.Constants;
import com.android.bhwallet.utils.HttpHelper;
import com.android.bhwallet.utils.UrlConfig;
import com.android.bhwallet.views.WiperSwitch;
import com.asuka.android.asukaandroid.AsukaTakePhotoActivity;
import com.asuka.android.asukaandroid.comm.utils.StringUtils;
import com.asuka.android.asukaandroid.http.EGRequestParams;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 蒋冬冬
 * 创建日期：2020/7/20
 * 邮箱：825814902@qq.com
 * 描述：
 */
public class WalletOpenActivity extends AsukaTakePhotoActivity {
    private Button open;
    private EditText name;
    private EditText idcard;
    private ImageView card1;
    private ImageView card2;
    private EditText tel;
    private EditText bank_card;
    private EditText password1;
    private EditText password2;
    //private EditText card_password;
    private TextView get_yzm;
    private EditText code;
    private TextView job;

    private WiperSwitch ws;

    private int clickIndex;
    private String cardPath1;
    private String cardPath2;

    private String merUserId;
    private String mUserId;
    private String orderId;
    private String jobId;

    private ImagePicker imagePicker = new ImagePicker();

    private int timeCount = 60;
    private final int TIME_START = 0X01;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case TIME_START:
                    if (timeCount == 0) {
                        get_yzm.setText("获取验证码");
                        get_yzm.setEnabled(true);
                    } else {
                        get_yzm.setText(timeCount + "s");
                        timeCount--;
                        sendEmptyMessageDelayed(TIME_START, 1000);
                    }
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_wallet_open);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            merUserId = bundle.getString("merUserId");
            mUserId = bundle.getString("mUserId");
        }

        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(false);


        name = findViewById(R.id.name);
        idcard = findViewById(R.id.idcard);
        card1 = findViewById(R.id.card1);
        card2 = findViewById(R.id.card2);
        tel = findViewById(R.id.tel);
        bank_card = findViewById(R.id.bank_card);
        password1 = findViewById(R.id.password1);
        password2 = findViewById(R.id.password2);
        //card_password = findViewById(R.id.card_password);
        ws = findViewById(R.id.ws);
        ws.setChecked(true);
        get_yzm = findViewById(R.id.get_yzm);
        code = findViewById(R.id.code);
        job = findViewById(R.id.job);

        open = findViewById(R.id.open);
    }

    @Override
    protected void initEvent() {
        get_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cardCheck();
            }
        });
        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitData();
            }
        });

        card1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickIndex = 1;
                startChooser();

            }
        });

        card2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickIndex = 2;
                startChooser();
            }
        });

        job.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(JobListActivity.class, "选择职业", null);
            }
        });

    }

    @Override
    protected void oberserMsg(String type, JSONObject object) {

    }

    private void startChooser() {
        if (Build.VERSION.SDK_INT > 22) {
            List<String> permissionList = new ArrayList<>();
            int check = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
                permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissionList.size() == 0) {
                imagePicker.startChooser(this, new ImagePicker.Callback() {
                    // 选择图片回调
                    @Override
                    public void onPickImage(Uri imageUri) {
                        upPic(getPathFromUri(WalletOpenActivity.this, imageUri));

                    }

                    // 裁剪图片回调
                    @Override
                    public void onCropImage(Uri imageUri) {

                    }

                    // 自定义裁剪配置
                    @Override
                    public void cropConfig(CropImage.ActivityBuilder builder) {

                    }

                    // 用户拒绝授权回调
                    @Override
                    public void onPermissionDenied(int requestCode, String[] permissions,
                                                   int[] grantResults) {
                    }
                });
            } else {
                ActivityCompat.requestPermissions(this,
                        permissionList.toArray(new String[permissionList.size()]), Constants.select_pic_and_crop);
            }
        }

    }


    private void cardCheck() {

        final String strName = name.getText().toString();
        if (StringUtils.isEmpty(strName)) {
            showWarning("请输入姓名");
            return;
        }

        final String strIdCard = idcard.getText().toString().trim();
        if (StringUtils.isEmpty(strIdCard)) {
            showWarning("请输入身份证号");
            return;
        }

        final String strBackCard = bank_card.getText().toString();
        if (StringUtils.isEmpty(strBackCard)) {
            showWarning("请输入银行卡号");
            return;
        }

        final String strTel = tel.getText().toString().trim();
        if (StringUtils.isEmpty(strTel)) {
            showWarning("请输入手机号码");
            return;
        }

        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("acctName", strName);
        para.addBodyParameter("acctNo", strBackCard);
        para.addBodyParameter("certNo", strIdCard);
        para.addBodyParameter("mobilePhone", strTel);
        HttpHelper.post(this, UrlConfig.CHECK_CARD, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                JSONObject object = JSON.parseObject(str);
                orderId = object.getString("orderId");
                timeCount = 60;
                handler.sendEmptyMessageDelayed(TIME_START, 1000);
                get_yzm.setEnabled(false);
            }

            @Override
            public void complete(String str) {

            }
        });

    }

    private void commitData() {
        final String strName = name.getText().toString();
        if (StringUtils.isEmpty(strName)) {
            showWarning("请输入姓名");
            return;
        }

        final String strIdCard = idcard.getText().toString().trim();
        if (StringUtils.isEmpty(strIdCard)) {
            showWarning("请输入身份证号");
            return;
        }

        if (StringUtils.isEmpty(cardPath1)) {
            showWarning("请上传人像面");
            return;
        }
        if (StringUtils.isEmpty(cardPath2)) {
            showWarning("请上传国徽面");
            return;
        }

        if (StringUtils.isEmpty(jobId)){
            showWarning("请选择职业");
            return;
        }

        final String strTel = tel.getText().toString().trim();
        if (StringUtils.isEmpty(strTel)) {
            showWarning("请输入手机号码");
            return;
        }

        String strCode = code.getText().toString().trim();
        if (StringUtils.isEmpty(strCode)) {
            showWarning("请输入验证码");
            return;
        }

        final String strBackCard = bank_card.getText().toString();
        if (StringUtils.isEmpty(strBackCard)) {
            showWarning("请输入银行卡号");
            return;
        }

//        final String cardPassword = card_password.getText().toString().trim();
//        if (StringUtils.isEmpty(cardPassword)) {
//            showWarning("请输入银行卡密码");
//            return;
//        } else if (cardPassword.length() != 6) {
//            showWarning("请输入6位银行卡密码");
//            return;
//        }


        final String strPassword1 = password1.getText().toString().trim();
        if (StringUtils.isEmpty(strPassword1)) {
            showWarning("请输入交易密码");
            return;
        } else if (strPassword1.length() != 6) {
            showWarning("请输入6位交易密码");
            return;
        }

        String strPassword2 = password2.getText().toString().trim();
        if (StringUtils.isEmpty(strPassword2)) {
            showWarning("请输入确认密码");
            return;
        }

        if (!strPassword1.equals(strPassword2)) {
            showWarning("两次密码不一致，请确认后重新输入");
            return;
        }

        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("acctName", strName);
        para.addBodyParameter("acctNo", strBackCard);
        para.addBodyParameter("certNo", strIdCard);

        para.addBodyParameter("IdImgFront", cardPath1);
        para.addBodyParameter("IdImgBack", cardPath2);
        para.addBodyParameter("workType",jobId);
        para.addBodyParameter("merUserId", merUserId);
        para.addBodyParameter("mobilePhone", strTel);
        para.addBodyParameter("orderId", orderId);
        para.addBodyParameter("password", strPassword1);
        //para.addBodyParameter("cardPassword", cardPassword);
        para.addBodyParameter("UserEa", ws.getNowStatus() ? "1" : "0");
        para.addBodyParameter("verifyNo", strCode);
        para.addBodyParameter("mUserId", mUserId);


        HttpHelper.post(this, UrlConfig.OPEN_WALLET, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                Bundle bundle = new Bundle();
                bundle.putBoolean("UserEa", ws.getNowStatus());
                bundle.putString("merUserId", merUserId);
                bundle.putString("job_name",job.getText().toString());
                bundle.putString("job_id",jobId);
                startActivity(WalletOpenSuccessActivity.class, "开通钱包", bundle);
                sendObseverMsg("update_user", new JSONObject());
                finish();
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    //   @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK) {
//            if (requestCode == 12) {
//                ArrayList<String> path = data.getStringArrayListExtra(GalleryActivity.PHOTOS);
//                upPic(path.get(0));
//
//            }
//        }

//    }

    private void upPic(final String path) {
        EGRequestParams para = new EGRequestParams();
        para.addBodyParameter("file", new File(path));

        HttpHelper.post(this, UrlConfig.UP_PIC, para, new HttpHelper.Ok() {
            @Override
            public void success(String str) {
                JSONObject object = JSON.parseObject(str);
                Bitmap bp = BitmapFactory.decodeFile(path);
                switch (clickIndex) {
                    case 1:
                        cardPath1 = object.getString("filePath");
                        card1.setImageBitmap(bp);
                        //ImageUtil.ShowIamge(card1, UrlConfig.BASE_IMAGE_URL +"/walletadmin"+ cardPath1);
                        break;
                    case 2:
                        cardPath2 = object.getString("filePath");
                        card2.setImageBitmap(bp);
                        //ImageUtil.ShowIamge(card2, UrlConfig.BASE_IMAGE_URL +"/walletadmin"+ cardPath2);
                        break;
                }
            }

            @Override
            public void complete(String str) {

            }
        });
    }

    @SuppressLint("NewApi")
    public static String getPathFromUri(final Context context, final Uri uri) {
        if (uri == null) {
            return null;
        }
        // 判斷是否為Android 4.4之後的版本
        final boolean after44 = Build.VERSION.SDK_INT >= 19;
        if (after44 && DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是Android 4.4之後的版本，而且屬於文件URI
            final String authority = uri.getAuthority();
            // 判斷Authority是否為本地端檔案所使用的
            if ("com.android.externalstorage.documents".equals(authority)) {
                // 外部儲存空間
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] divide = docId.split(":");
                final String type = divide[0];
                if ("primary".equals(type)) {
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat("/").concat(divide[1]);
                    return path;
                } else {
                    String path = "/storage/".concat(type).concat("/").concat(divide[1]);
                    return path;
                }
            } else if ("com.android.providers.downloads.documents".equals(authority)) {
                // 下載目錄
                final String docId = DocumentsContract.getDocumentId(uri);
                if (docId.startsWith("raw:")) {
                    final String path = docId.replaceFirst("raw:", "");
                    return path;
                }
                final Uri downloadUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docId));
                String path = queryAbsolutePath(context, downloadUri);
                return path;
            } else if ("com.android.providers.media.documents".equals(authority)) {
                // 圖片、影音檔案
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] divide = docId.split(":");
                final String type = divide[0];
                Uri mediaUri = null;
                if ("image".equals(type)) {
                    mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    mediaUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                    return null;
                }
                mediaUri = ContentUris.withAppendedId(mediaUri, Long.parseLong(divide[1]));
                String path = queryAbsolutePath(context, mediaUri);
                return path;
            }
        } else {
            // 如果是一般的URI
            final String scheme = uri.getScheme();
            String path = null;
            if ("content".equals(scheme)) {
                // 內容URI
                path = queryAbsolutePath(context, uri);
            } else if ("file".equals(scheme)) {
                // 檔案URI
                path = uri.getPath();
            }
            return path;
        }
        return null;
    }

    public static String queryAbsolutePath(final Context context, final Uri uri) {
        final String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                return cursor.getString(index);
            }
        } catch (final Exception ex) {
            ex.printStackTrace();
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String type = bundle.getString("type");
                if ("job".equals(type)) {
                    job.setText(bundle.getString("name"));
                    jobId = bundle.getString("id");
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

}
